//
// Created by admin on 2024/7/6.
//
#include "linklist.h"


Node *createNode(Node *prev, void *data, Node *next, int root){
    Node *pNode = (Node *)malloc(sizeof(Node));
    pNode->prev = prev;
    pNode->data = data;
    pNode->next= next;
    pNode->root = root;
    return pNode;
}

LinkList *create(void  (*freeData)(void *data)){
    LinkList *linkList = (LinkList *) malloc(sizeof(LinkList));
    linkList->size = 0;
    linkList->root = NULL;
    linkList->freeData = freeData;
    return linkList;
}

void addFirst(LinkList *linkList, void *data){

    if(linkList == NULL){
        printf("linklist is null");
        return;
    }

    addLast(linkList, data);
    Node *rootNode = linkList->root;
    rootNode->root = 0;
    Node *lastNode = rootNode->prev;
    lastNode->root = 1;
    linkList->root = lastNode;

}

void addLast(LinkList *linkList, void *data){

    if(linkList == NULL){
        printf("linklist is null");
        return;
    }

    linkList->size += 1;
    Node *rootNode = linkList->root;
    if (rootNode == NULL){
        rootNode = createNode(NULL, data, NULL, 1);
        rootNode->prev = rootNode;
        rootNode->next = rootNode;
        linkList->root = rootNode;
    }else{
        Node *pNode = createNode(NULL, data, NULL, 0);
        Node *lastNode = rootNode->prev;
        lastNode->next = pNode;
        rootNode->prev = pNode;
        pNode->next = rootNode;
        pNode->prev = lastNode;
    }

}



void *indexGet(int i, LinkList *linkList){
	Iterator iter; iterator(&iter, linkList);
	int k=0;
	while(hasNext(&iter)){
		if(k == i){
			return next(&iter);
		}else{
			k += 1;
		}
	}
	return NULL;
}

void iterator(Iterator *iter,LinkList *linkList){
    iter->pos = linkList->size;
    iter->node = linkList->root;
    iter->linkList = linkList;
}

int hasNext(Iterator *iter){
    if (iter->node != NULL && iter->pos > 0){
        Node *curNode = iter->node;
        iter->node = curNode->next;
        iter->pos -= 1;
        return 1;
    }
    return 0;
}

void *next(Iterator *iter){
    Node *curNode = iter->node->prev;
    return curNode->data;
}

void delNode(Iterator *iter){
    Node *curNode = iter->node->prev;

    Node *rootNode = curNode->next;
    Node *prev = curNode->prev;
    rootNode->prev = prev;
    rootNode->root = 1;
    prev->next = rootNode;

    iter->linkList->root = rootNode;
    iter->linkList->size -= 1;

    if (iter->linkList->size == 0){
        iter->linkList->root = NULL;
    }

    curNode->next = NULL;
    curNode->prev = NULL;
    iter->linkList->freeData(curNode->data);
    free(curNode);
}




















